import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import fp from 'lodash/fp';

dayjs.extend(duration);

function padStartZero(timeStr = 0, zeroLength = 2) {
  if (Number(timeStr) < 0) {
    return `-${fp.padCharsStart('0', zeroLength, `${Math.abs(timeStr)}`)}`;
  }

  return fp.padCharsStart('0', zeroLength, `${timeStr}`);
}

/**
 * getTimeDuration方法的选项
 */
interface IGetTimeDurationOptions {
  /** 起始时间戳 毫秒 */
  startTimeStamp?: number,
  /** 结束时间戳 毫秒 */
  endTimeStamp?: number,
}

/**
 * getTimeDuration方法的返回值
 */
interface IGetTimeDurationResult {
  /** 天部分 */
  DDMax: string,
  /** 0-30天部分 */
  DD: string,
  /** 小时部分 */
  HHMax: string,
  /** 0-23小时部分 */
  HH: string,
  /** 分钟部分 */
  mmMax: string,
  /** 0-59分钟部分 */
  mm: string,
  /** 秒部分 */
  ssMax: string,
  /** 0-59秒部分 */
  ss: string,
  /** 毫秒部分 */
  SSSMax: string,
  /** 0-999毫秒部分 */
  SSS: string,
  /**  Duration实例 */
  duration: duration.Duration,
}

/**
 * 根据起始时间和结束时间得到差值信息
 * @exports
 * @since 1.1.4
 * @param {IGetTimeDurationOptions} options 选项
 * @returns {IGetTimeDurationResult}
 */
export default function getTimeDuration({
  startTimeStamp = 0,
  endTimeStamp = 0,
}:IGetTimeDurationOptions = {}):IGetTimeDurationResult {
  const diff = endTimeStamp - startTimeStamp;
  const timeDuration = dayjs.duration(diff);

  const DDMax = padStartZero(parseInt(`${timeDuration.asDays()}`, 10));
  const DD = padStartZero(parseInt(`${timeDuration.days()}`, 10));
  const HHMax = padStartZero(parseInt(`${timeDuration.asHours()}`, 10));
  const HH = padStartZero(parseInt(`${timeDuration.hours()}`, 10));
  const mmMax = padStartZero(parseInt(`${timeDuration.asMinutes()}`, 10));
  const mm = padStartZero(parseInt(`${timeDuration.minutes()}`, 10));
  const ssMax = padStartZero(parseInt(`${timeDuration.asSeconds()}`, 10));
  const ss = padStartZero(parseInt(`${timeDuration.seconds()}`, 10));
  const SSSMax = padStartZero(timeDuration.asMilliseconds(), 3);
  const SSS = padStartZero(timeDuration.milliseconds(), 3);

  return {
    DDMax,
    DD,
    HHMax,
    HH,
    mmMax,
    mm,
    ssMax,
    ss,
    SSSMax,
    SSS,
    duration: timeDuration,
  };
}
